package top.honlnk.czuan.common.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.honlnk.czuan.common.exception.CustomException;

@Slf4j
@Component
public class GetBaiduAccessTokenUtil {
    public String getAccessToken(String api_key, String secret_key) {
        String publicUrl = "https://aip.baidubce.com/oauth/2.0/token";
        String grantType = "client_credentials";
        String url = publicUrl + "?grant_type=" + grantType + "&client_id=" + api_key + "&client_secret=" + secret_key;
        String result = HttpUtil.get(url);
        JSONObject resultJSONObj = JSONUtil.parseObj(result);
        log.info("获取结果: {}", resultJSONObj);
        if (resultJSONObj.getStr("access_token") == null) {
            throw new CustomException("获取百度翻译access_token失败");
        }
        return JSONUtil.parseObj(result).getStr("access_token");
    }
}
